//
//  AppDelegate.swift
//  XinLangWeibo10
//
//  Created by 白利兵 on 15/10/15.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 创建Window
        window = UIWindow(frame: UIScreen .mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        // 设置控制器可见
        window?.makeKeyAndVisible()
        // 设置根控制器
        setRootViewController()
        // 设置全局外观
        setupApperance()
        // 添加通知观察者
        NSNotificationCenter.defaultCenter().addObserverForName(WBNotificationSwithRootView,
            object: nil, // 通知对象，监听发出通知的对象，nil默认接收任何对象发出的通知
            queue: nil)  // 队列，nil默认为主线程
            {[weak self](NSNotification) -> Void in // weak self防止循环引用
                // 进入登录界面
                let vc = NSNotification.object != nil ? WelcomViewController() : HMWeiboTabBarController()
                self!.window?.rootViewController = vc
        }

        return true
    }
    
    // MARK - 检查版本更新
    private func checkVersionUpdate() {
        // 获取当前的版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)!

        // 拿到键值
        let appVersionKey = "appVersionKey"
        // 获取之前的版本
        let priviousVersion = NSUserDefaults.standardUserDefaults().doubleForKey(appVersionKey)
        print(priviousVersion)
        print(version)
        // 保存当前的版本
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: appVersionKey)
        // 比较版本
        if version > priviousVersion {
            print("版本升级")
            window?.rootViewController = newFeatureViewController()
        }
        else {
            print("版本未升级")
            // 进入欢迎界面
            window?.rootViewController = WelcomViewController()
        }
    }
    // 设置全局外观
    private func setupApperance() {
        UINavigationBar.appearance().tintColor = GlobalColor
        UITabBar.appearance().tintColor = GlobalColor
    }
    
    // 设置跟控制器
    private func setRootViewController() {
        // /Users/bailibing/Library/Developer/CoreSimulator/Devices/D4BBD0A5-93EC-486D-8993-5974BBE5850C/data/Containers/Data/Application/35E43584-CBC3-45E6-8BA0-FEB7FAAB1552/Documents/account.plist
        // 判断登录状态
        let isLogon = UserAccountViewModel.shareUserAccount.logon
        if isLogon {
            // 检查版本是否更新
            checkVersionUpdate()
        }
        else {
            // 进入欢迎界面
            window?.rootViewController = HMWeiboTabBarController()
        }
    }
    func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
        print("viewWill")
        return true
    }

}

